import base64
import hashlib
import json
import random

import datetime
import time
import uuid


class ChatGPTPoW:
    def get_answer(self, payload):
        if payload and 'seed' in payload and 'difficulty' in payload and 'user_agent' in payload:
            seed = payload['seed']
            user_agent = payload['user_agent']
            difficulty = payload['difficulty']

            if isinstance(seed, str) and isinstance(difficulty, str):
                wh = random.randint(1000, 3000)
                config = self._get_config(wh, user_agent)

                return "gAAAAAB" + self._generate_answer(seed, difficulty, config)
        return None

    @staticmethod
    def _generate_answer(seed, difficulty, config):
        start_time = time.time()
        difficulty_len = len(difficulty)

        for attempt in range(0,92438):
            config[3] = attempt

            json_str = json.dumps(config, ensure_ascii=False, separators=(',', ':'))
            answer = base64.b64encode(json_str.encode('utf-8'))

            encoded_input = seed.encode('utf-8') + answer
            hasher = hashlib.sha3_512()
            hasher.update(encoded_input)
            candidate = hasher.hexdigest()
            # print(seed, "answer: ",  answer)
            # print(encoded_input)ate[:difficulty_len], difficulty)
            if candidate[:difficulty_len] <= difficulty:
                print(json.dumps(config, ensure_ascii=False))
                print(
                    "difficulty: {}, attempt: {}, 耗时:{}".format(difficulty, attempt, time.time() - start_time, )
                );
                return answer.decode('utf-8')

    @staticmethod
    def _get_config(wh, user_agent):
        now_utc = datetime.datetime.now(datetime.UTC)

        china_offset = datetime.timedelta(hours=8)
        now_china = now_utc + china_offset

        formatted_time = now_china.strftime(f'%a %b %d %Y %H:%M:%S GMT+0800 (中国标准时间)')
        print("formatted_time", formatted_time)

        return [
            wh, formatted_time, 2172649472, 50, user_agent,
            "https://tcr9i.openai.com/v2/0A1D34FC-659D-4E23-B17B-694DCFCF6A6C/api.js", None, "zh-CN", "zh-CN", 16,
            "locks−[object LockManager]", "location", "onunhandledrejection", 2707.9000000059605, str(uuid.uuid4())
        ]
